﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Server;
using System;
using System.Linq;
using System.Text;
using System.Threading;

namespace SubscribeConsumer1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($@"发布/订阅模式----------------消费者1接收到消息---------------");


            Consumer.ReciveMsg();
            Console.ReadLine();
        }
    }

    class Consumer
    {
        private static readonly ConnectionFactory rabbitMqFactory = CommonConnectionFactory.rabbitMqFactory;

        public static void ReciveMsg()
        {

            using (IConnection conn = rabbitMqFactory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    string ExchangeName = "订阅交换机";
                    channel.ExchangeDeclare(exchange: ExchangeName, type: ExchangeType.Fanout);

                    var queueName = channel.QueueDeclare().QueueName;
                    channel.QueueBind(queue: queueName, exchange: ExchangeName, routingKey: "");

                    Console.WriteLine(" [*] 订阅交换接收消息1 [*]");

                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += (model, ea) =>
                    {
                        var body = ea.Body.ToArray();
                        var message = Encoding.UTF8.GetString(body.ToArray());
                        Console.WriteLine(" [x] {0}", message);
                    };
                    channel.BasicConsume(queue: queueName, autoAck: true, consumer: consumer);
                    Console.ReadLine();
                }
            }
        }
    }
}
